<?php
/**
 * Created by PhpStorm.
 * user: yuki
 * Date: 2017/6/21
 * Time: 09:08
 */

namespace app\common\controller;


use think\Controller;
use think\Db;
use think\Request;
use WxSDK\UnifiedOrder;
use WxPay\lib\Api;
use WxPay\JsApiPay;
use WxPay\lib\Data;
use app\common\model\Base;

class Commoncontroller extends Controller
{
    const DELETE_NO = 1;//使用中
    const DELETE_HID = 2;//禁用
    const DELETE_YES = 3;//删除



    public function _initialize()
    {
        parent::_initialize();

        $request = Request::instance();
        if (!defined('MODULE_NAME')) {
            define('MODULE_NAME', $request->module()); // 当前模块名称是
        }

        if (!defined('CONTROLLER_NAME')) {
            define('CONTROLLER_NAME', $request->controller()); // 当前模块名称是
        }

        if (!defined('ACTION_NAME')) {
            define('ACTION_NAME', $request->action()); // 当前模块名称是
        }

        //define('CONTROLLER_NAME', $request->controller()); // 当前控制器名称
        // define('ACTION_NAME', $request->action()); // 当前操作名称是

        header("Access-Control-Allow-Origin:*");

        $domain = 'http://' . $_SERVER['HTTP_HOST'] . substr($_SERVER['SCRIPT_NAME'], 0, strrpos($_SERVER['SCRIPT_NAME'], '/'));
        defined('APP_DOMAIN') || define('APP_DOMAIN', $domain);
        $paginate = Config('paginate');
        $this->page_size = $paginate['list_rows'];
        $this->assign('page_size', $paginate['list_rows']);
        $devietype = $this->get_device_type();

        $downloadUrl = "http://a.app.qq.com/o/simple.jsp?pkgname=com.youzai.gaosu";

        $this->assign('downloadUrl', $downloadUrl);
        $this->assign('device', $devietype);


    }


    function get_device_type()
    {
        //全部变成小写字母
        $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
        $type = 'other';
        //分别进行判断
        if (strpos($agent, 'iphone') || strpos($agent, 'ipad')) {
            $type = '1';
        }

        if (strpos($agent, 'android')) {
            $type = '2';
        }
        return $type;

    }



    /********************************后台函数********************************************/

    /**
     * 判断控制器+方法
     * @param $controllerName 当前访问的控制器
     * @param $actionName 当前访问的方法
     * @param $adminLog 记录操作日志的基础建设
     * @param return array  返回adminLog中索引的数组
     */
    protected function checkAdminLog($controllerName, $actionName, $adminLog)
    {

        try {

            if (isset($adminLog[$controllerName])) {
                $item = $adminLog[$controllerName];

                if (is_array($item)) {
                    // $item = $this->arrayToLower($item);
                    foreach ($item as $key => $actions) {

                        if (in_array($actionName, $actions['action'])) {
                            return $item[$key];
                        }
                    }
                    return false;
                } elseif (is_string($item)) {
                    return false;
                }
            }
        } catch (Exception $e) {
            return $e->getMessage();
        }


    }

    /********************************后台函数********************************************/


    /********************************公用函数********************************************/
    /**
     * 管理员列表
     */
    public function admin_list()
    {
        $list = Db::name('admin')->where(array('is_deleted' => 1))->select();

        return $list;
    }

    /**
     * @param $fid  详情id
     * @return 反馈详情
     */
    public function getFeedback($fid)
    {
        $feedback = model('feedback')->field('feedback.*,user.name ,user.phone')
            ->join('user', 'user.id=feedback.userid')
            ->order('create_time desc')
            ->where(array('feedback.id' => $fid))->find();

        return $feedback;

    }

    /**
     * @param $option
     * 获取文章
     */
    public function getArticle($option)
    {

        $article = model('article')->where($option)->find();
        return $article;
    }

    /**
     * @param $patient_part_lat
     * @param $type 1:检查记录里   只显示一个检查维度部位 2：检查详情里显示多个
     * @return string
     */
    protected function getPart_lat($patient_part_lat, $type)
    {

        $patient_part_lat_arr = json_decode($patient_part_lat, true);
//        var_dump($patient_part_lat_arr);
        if ($patient_part_lat_arr) {
            //组合后的新名字  eg 立位胸部...
            $part_lat_name = '';
            $str = '';
            $i = 1;
            foreach ($patient_part_lat_arr as $key => $part_lat) {
                if ($type == 1) {
                    //维度
                    $lat_arr = array_keys($part_lat);
                    //部位
                    $part_arr = array_values($part_lat);
                    $patient_case_part = $this->getPatient_case_type($part_arr[0]);
                    $part_name = $patient_case_part['name'];
                    $patient_case_lat = $this->getPatient_case_type($lat_arr[0]);
                    $lat_name = $patient_case_lat['name'];
                    if ($i == 1) {
                        if (count($patient_part_lat_arr) > 1) {
                            $str = '...';
                        }
                        $part_lat_name .= $lat_name . $part_name . $str;
                        break;
                    }
                } else {
                    if ($part_lat) {
                        foreach ($part_lat as $key2 => $part_lat_value) {
                            //立位胸部
                            $patient_case_part = $this->getPatient_case_type($key2);
                            $part_name = $patient_case_part['name'];
                            $patient_case_lat = $this->getPatient_case_type($part_lat_value);
                            $lat_name = $patient_case_lat['name'];
                            $part_lat_name .= $part_name . $lat_name;

                        }
                    }
                }

            }
        } else {
            $part_lat_name = '';
        }
        return $part_lat_name;
    }

    /********************************公用函数********************************************/

    /*************************接口函数********************************/


    public function getList(Base $Model, $where, $size = null, $order = '')
    {
        $Model2 = clone $Model;
        $list['count'] = $Model->getTotal($where);
        $list['list'] = $Model2->getList($where, $this->page, $size, $order);
        return $list;
    }
    /*************************接口函数********************************/


    /********************************用户端函数start********************************************/
    /**
     * @param $option
     * 获取个人信息
     */
    public function getUser_info($option)
    {
        $user_info = model('user')
            ->where($option)
            ->find();
        return $user_info;
    }

    /**
     * @param $option
     * @return mixed
     * 根据根据条件查询多少家属
     */
    public function getUserfamilycount($option)
    {
        $option['is_deleted'] = 1;
        $userfamily_count = model('Userfamily')
            ->where($option)
            ->count();
        return $userfamily_count;
    }

    /**
     * @param $option
     * @return获取家属的病例记录数
     */
    public function getall_Userfamilycasecount($option)
    {
        /*
         */
        $userfamilylist = $this->getUserfamilylist($option, 0, Null);
        $record_count = 0;
        foreach ($userfamilylist as $key => $value) {
            $userfamily_info = $this->getPatientID_Bydocnum($value['document_num']);
            $optionnew['patient_id'] = $userfamily_info['id'];
            $optionnew['is_deleted'] = 1;
            $value['record_count'] = $this->getUserfamilycase_count($optionnew);
            $record_count += $this->getUserfamilycase_count($optionnew);
        }

        return $record_count;
    }

    /**
     * @param $document_num
     * 根据身份证查家属
     */
    public function getUserfamily_Bydocnum($document_num)
    {
        $userfamily_info = model('userfamily')->where('document_num', $document_num)->find();
        return $userfamily_info;
    }
    /**
     * @param $document_num
     * 根据身份证查家属
     */
    public function getPatient_Bydocnum($document_num)
    {
        $userfamily_info = model('userfamily')
            ->field("patient.id")
            ->join("patient",'patient.document_num=user_family.document_num')
            ->where('user_family.document_num', $document_num)->find();
        return $userfamily_info;
    }

    /**
     * @param $document_num
     * 根据身份证查病人ID以及信息
     */
    public function getPatientID_Bydocnum($document_num)
    {


        $patient_info = model('patient')->where('document_num', $document_num)->find();
        return $patient_info;
    }

    /**
     * @param id
     * 根据ID查病人信息
     */
    public function getPatient_ById($id)
    {
        $patient_info = model('patient')->where('id', $id)->find();
        return $patient_info;
    }

    /**
     * @param $type_id
     * 根据id检查部位、检查维度
     */
    public function getPatient_case_type($type_id)
    {
        $patient_case_type = model('patient_case_type')->field('name')->where('id', $type_id)->find();
        return $patient_case_type;
    }

    /**
     * 获取某医生所建立的检查项设置
     */
    public function getCase_type($option)
    {
        $option['is_deleted'] = 1;
        $patient_case_type = model('patient_case_type')->where($option)->select();
        return $patient_case_type;
    }

    /**
     * @param $option
     * @return mixed
     * 根据条件查找所属用户或者医生的家属列表
     */
    public function getUserfamilylist($option, $page = 0, $listrow = 10)
    {
        $option['is_deleted'] = 1;
        $userfamily_list = model('Userfamily')->field('name,sex,id,document_num')
            ->where($option)
            ->page($page, $listrow)
            ->select();
        return $userfamily_list;
    }

    /**
     * @param $option
     * @return 某亲人的检查记录数
     */
    public function getUserfamilycase_count($option)
    {
        $option['is_deleted'] = 1;
        $userfamily_case_count = model('Patientcase')->where($option)->count();
        return $userfamily_case_count;
    }

    /**
     * @param $option
     * @return 某家属/病人的检查记录
     */
    public function getCase_list($option, $page)
    {
        $option['is_deleted'] = 1;
        $userfamily_case_count = model('Patientcase')->where($option)->page($page, 10)->order('check_time desc')->select();
        return $userfamily_case_count;
    }

    /**
     * @param $id
     * @return 根据id获取病人病例的详情
     */
    public function getPatientcase_info($id)
    {
        $patientcase_info = model('Patientcase')->field('patient_case.*, doctor.name as doctor_name')->join("doctor", "patient_case.doctor_id = doctor.id")
            ->where('patient_case.id', $id)
            ->find();
        return $patientcase_info;
    }

    /**
     * @param $id
     * @return 获取家属信息
     */
    public function getUserfamilyById($id)
    {
        $userfamily_info = model('Userfamily')->where('id', $id)->find();
        return $userfamily_info;
    }

    /**
     * @param $id
     * 删除家属信息 包括病例
     */
    public function delete_userfamily($id)
    {
        $data = array('is_deleted' => self::DELETE_YES);
        model('userfamily')->allowField(true)->save($data, ['id' => $id]);

        //删除病例

    }

    /**
     * @param $cid --病例id
     * 获取病人信息以及病例
     */
    public function getPatient_info_case($cid)
    {
        //病例信息
        $patientcase_info = $this->getPatientcase_info($cid);

        $patientcase_info['patient_part_lat'] = json_decode($patientcase_info['patient_part_lat'], true);
        //  print_r($patientcase_info['patient_part_lat']);
        // print_r($patientcase_info['patient_part_lat']);

        //   exit;*/

        $patient_info = $this->getPatient_ById($patientcase_info['patient_id']);

        //检查部位维度

        // $patientcase_info['patient_part_lat'] = $this->getPart_lat($patientcase_info['patient_part_lat'], 2);

        //获取检查类型
        $patient_case_type = $this->getPatient_case_type($patientcase_info['patient_case_type']);
        $patientcase_info['patient_case_type'] = $patient_case_type['name'];

        $this->assign('patientcase_info', $patientcase_info);
        $this->assign('patient_info', $patient_info);

    }

    /**
     * @param $cid
     * 根据病例id 获取电子报告
     */
    public function getPatient_report($cid)
    {
        $patientcase_info = $this->getPatientcase_info($cid);
        //取出电子报告
        $electronic_report_arr = json_decode($patientcase_info['electronic_report'], true);
        $this->assign('electronic_report_arr', $electronic_report_arr);

    }

    /**
     * @param $cid
     * 根据病例id 获取电子胶片
     */
    public function getPatient_film($cid)
    {
        $patientcase_info = $this->getPatientcase_info($cid);
        //取出电子报告
        $electronic_film_arr = json_decode($patientcase_info['electronic_film'], true);
        //print_r($electronic_film_arr);
        $this->assign('electronic_film_arr', $electronic_film_arr);

    }
    /********************************用户端函数end********************************************/



    protected function AliyunSendSMS($tel, $code, $templateCode, $signName)
    {
        include('./extend/Aliyun/Aliyunsendsms.php');
        $SmsDemo = new \Aliyunsendsms();

        session('msg_code',$code);
        $response = $SmsDemo->sendSms($signName, $templateCode, $tel, ["code" => $code]);
        //print_r($response);//die;
        $res = $response->Code;
        //  print_r($response);
        if ($res == 'OK') {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 检验是否要发送短信问题
     **/
    protected function checkSendMsg($controllerName, $actionName, $record_id, $isSendMsg)
    {

        $isSendMsg = $this->checkAdminLog($controllerName, $actionName, $isSendMsg);

        if ($isSendMsg) {
            $sendMsgName = $isSendMsg['func']($record_id);
/*var_dump($sendMsgName);
die();*/
            $aliMsg = Config('aliMsg');
            $templateCode = $aliMsg['tpl_code'][$isSendMsg['msg_type']];
            $signName = $aliMsg['signName'];
            if ($sendMsgName) {
                $code = '111111';
                // print_r($templateCode);
                $sendMsg = $this->AliyunSendSMS($sendMsgName, $code, $templateCode, $signName);
                //  print_r($result_msf);

                if ($sendMsg) {
                    return true;
                } else {
                    return false;
                }

            }

        }
        return true;
    }


    ///
    public function uploadDcmByJs($num)
    {

        $domain = 'http://' . $_SERVER['HTTP_HOST'] . substr($_SERVER['SCRIPT_NAME'], 0, strrpos($_SERVER['SCRIPT_NAME'], '/'));

        $html = '';
        $html_name = "electronic_film[{$num}]";
        $html_name_class = "pic_dec_{$num}";
        $html .= " <style>
                .{$html_name_class} {

                display: inline-block;
                margin-left: 5px;
                margin-bottom: 5px;
                position: relative;
                width: 150px;

                }

                .{$html_name_class}:hover .dcmDel{
                display: block;
            }

            </style>";
        $html .= '

            <div class="pic_box" id="img_box_film_' . $num . '">
                <span>部位： </span>
                <div class="mini_theme">
							<input type="text" name="' . $html_name . '[report_name]">
						</div>
						<em class="decrease_btn"></em>

                 <div class="jiaopian_box">
                    <div class="up_box" id="electronic_film_' . $num . '">
                        <div class="up_btn">
                            <span>上传照片</span>

                        </div>
                    </div>

                </div>



            </div>';


        $html .= " <script src='" . $domain . "/public/static/common/webuploader/webuploader.min.js'></script>";
        $html .= " <script src='" . $domain . "/public/static/index/js/record.js'></script>";
        $html .= " <script src='" . $domain . "/public/static/common/dwv/dwv-0.22.0.min.js'></script>
            <script>
                //图片上传
                var uploader = WebUploader.create({
                    auto: true,
                    swf:'{$domain}/public/static/common/webuploader/lib/webuploader/Uploader.swf',
                    server:'" . url('common/upload/uploadFile') . "',
                    pick:'#electronic_film_" . $num . "',
                    fileVal:'pic',
                    fileNumLimit:'5',
                    duplicate :true,
                     accept : {
                                title:'格式不正确',
                                extensions:'dcm'
                            }
                    })

                    uploader.on('uploadSuccess', function(file, response){
                //console.log(response);
                if (response.error == 0) {
                  var length = $('.pic_dec_{$num}').length;
                  var length = Number(length)+1;
console.log(length)
                 var url = response.url;
                     var html = '<div class=pic_dec_{$num}>';
                     html += ' <div class=dcmDel><img src={$domain}/public/static/index/imgs/dcmDel.png></div>';
                     html += ' <div id=dwv_{$num}_'+length+'>';
                     html += ' <div class=layerContainer>';
                     html += ' <canvas class=imageLayer></canvas>';
                     html += ' </div>';
                     html += ' </div>';
                     html += ' </div>';

                     html += '<input type=hidden class=body_album name=" . $html_name . "[img][] value='+url+' >';

                   $('#img_box_film_{$num}').append(html);
						init_dicom({$num},length,url)
                    ";

        /*  $html .= '
            $([name="'.$fileName.'"]).each(function(){
            console.log($(this).val());
                  //  arr.push($(this).val());
                })
                 console.log(arr);
                // load dicom data
                app.loadURLs(arr);'；*/
        $html .= '    }
        });';


        $html .= "    uploader.on('error', function (type) {
                            if (type == 'Q_TYPE_DENIED') {
                                layer.msg('请上传DCM格式文件');
                            }else {
                                layer.msg('上传出错！请检查后重新上传！错误代码'+type);
                            }

                        });
            //删除图片
        $('body').on('click', '.dcmDel', function(){
            $(this).parent().remove();
            uploader.trigger('fileDequeued');
        })

            $('.new_huanzhe_record .list_box .list  .pic_dec').mouseenter(function(){
            $(this).find('em').show();
        })
        $('.new_huanzhe_record .list_box .list  .pic_dec').mouseleave(function(){
            $(this).find('em').hide();
        })


        $(function(){


        $(document).on('mouseenter','.new_huanzhe_record .list_box .list .pic_dec',function(){
            $(this).find('em').show();
        });
        $(document).on('mouseleave','.new_huanzhe_record .list_box .list .pic_dec',function(){
            $(this).find('em').hide();
        });
    })
        </script>";

        return $html;
    }


    /**
     * 产生用户的id_num
     */
    public function generateQrcode($url,$name){

        require_once  EXTEND_PATH."/qrcode/phpqrcode.php";


        //$url = APP_DOMAIN."/wei/user/check_invite/id/".$id_num;
        $outFile = "public/qrcode/".time().$name.'.png';

        \QRcode::png($url,$outFile,'',5);


        return $outFile;
    }

}

        
        
        
        
        
        
        
        